from . import api
from flask import request, jsonify, current_app, Response, stream_with_context
from myapp.models import get_conn, ImageTable
from sqlalchemy import select
import requests
from urllib.parse import quote

db_session = get_conn()

def load_file(url):

    try:
        response = requests.get(url=url, stream=True)
        for chunk in response.iter_content(chunk_size=512):
                if chunk:
                    yield chunk
    except Exception as e:
        current_app.logger.error("下载服务异常，异常信息：{}".format(e))      


@api.route("/updown")
def down_file():

    id = request.args.get("id")
    
    if not id:
        return jsonify(status_code=302, msg="参数值缺失！")
    image_tb = ImageTable.image_tb
    try:
        result = db_session.execute(select(image_tb.c.image_name, image_tb.c.image_url).where(image_tb.c.id==int(id))).first()
    except Exception as e:
        current_app.logger.error("服务器异常，异常信息：{}".format(e))
        return jsonify(status_code=500, msg="服务器异常，异常信息：{}".format(e))
    
    if not result:
        return jsonify(status_code=200, msg="图片不存在！")
    
    file_name, down_url = result
   
    file_end = down_url.split(".")[-1]
    response  =  Response(stream_with_context(load_file(down_url)))
    response.headers[ 'content-type' ]  =  'application/octet-stream;charset:utf-8'
    response.headers["Content-disposition"] = 'attachment; filename=%s' % (quote(file_name + "." + file_end))
    return  response
